<?php
namespace app\index\controller;

use think\Request;
use think\Controller;
use think\Session;

//店铺微信登陆
class Shoplogin extends Controller{

	public function index(){
		
		if(!__iswechat()){
			$this->error('请在微信中登陆');
		}
		
		$cfg = \ServerHelper::GetWeChatConfig();
		if(!isset($cfg['appid'])){
			__log('登录：没有设置微信appid','weixin');
			$this->error('系统错误');
			exit();
		}
		
		$appid = $cfg['appid'];
		
		$request = Request::instance();
		
		$redirect_uri = urlencode($request->domain() . url('Shoplogin/wechat_redirect'));
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize";
		$url.="?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		
		$this->redirect($url);
	}
	
	public function wechat_redirect(){
		//载入配置信息
		$cfg = \ServerHelper::GetWeChatConfig();
		if(
			!isset($cfg['appid']) || 
			!isset($cfg['appsecret'])
			){
			__log('登录：没有设置微信appid或appsecret','weixin');
			$this->error('系统错误');
			exit();
		}
		$appid = $cfg['appid'];
		$appsecret = $cfg['appsecret'];
		
		//拉取请求
		$request = Request::instance();

		//第一步返回的 得到了 Code
		$code = $request->param('code','');
		if($code == ''){
			$this->error('登录发起失败');
		}

		//第二步：通过code换取网页授权access_token
		$url ="https://api.weixin.qq.com/sns/oauth2/access_token";
		$url.="?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
		$info = $this->getJson($url);
		if(!isset($info['refresh_token'])){
			$this->error('登陆发起失败');
		}

		//第三步：刷新access_token（如果需要）
		$refresh_token = $info['refresh_token'];
		$url = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
		$url.= "?appid=$appid&grant_type=refresh_token&refresh_token=$refresh_token";
		$info = $this->getJson($url);
		if(
			!isset($info['access_token']) || 
			!isset($info['openid'])
		){
			$this->error('登陆发起失败');
		}

		//第四步：拉取用户信息(需scope为 snsapi_userinfo)
		$access_token = $info['access_token'];
		$openid = $info['openid'];
		$url = "https://api.weixin.qq.com/sns/userinfo";
		$url.= "?access_token=$access_token&openid=$openid&lang=zh_CN";
		$info = $this->getJson($url);

		if(!isset($info['openid'])){
			$this->error('登陆发起失败');
		}

		//后端登陆注册流程
		$param = [
			'wechatid' => $openid,
			'wechatname' => $info['nickname'],
			'headimg' => $info['headimgurl'],
			'shopid' => Session::get('shop_id')
		];
		//注册或登陆，得到agentid、status
		$response = \ServerHelper::post('shop_wechatlogin',$param);
		$data = $this->J($response);
		if(empty($data['flag'])){
			__log('[shopwelogin][提交微信信息到后端失败]:'.$response,'weixin');
			$this->error('系统错误');
		}else{
			$agentInfo = $data['data'];
			Session::set('shop_id',$agentInfo['agentid']);
			Session::set('cust_id',$agentInfo['customerid']);
			$this->redirect('Shop/index');
		}
	}
	
	private function getJson($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		return json_decode($output, true);
	}
	
	
	protected function J($list){
		$data = json_decode($list,true);
		if(!isset($data['flag'])){
			exit('connect error');
		}
		return $data;
	}
	

	
}
